package com.jic.market.impl.rest.discountamount.processor;

import com.jic.market.common.util.Money;
import com.jic.market.entity.PromotionRuleEntity;
import com.jic.market.impl.rest.discountamount.model.PromotionAmountModel;
import com.jic.market.impl.rest.discountamount.po.GoodsPo;
import com.jic.market.mapper.PromotionRuleEntityMapper;
import com.jic.market.request.rest.discountamount.DiscountAmountQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 满量-满量减运费
 * @author yinhaijun
 * @date: 2020/4/7
 */
@Service("FullNumReduceLogisticsAmountProcessor")
public class FullNumReduceLogisticsAmountProcessor extends AmountProcessor {

    @Autowired
    private PromotionRuleEntityMapper promotionRuleEntityMapper;

    @Override
    protected Boolean isCondition(PromotionAmountModel promotionAmountModel, GoodsPo goodsPo, String thirdUserId) {
        if(!checkCommonLimitRule(promotionAmountModel.getPromotionId(), goodsPo.getSkuId(), goodsPo.getNum(), thirdUserId)){
            return false;
        }

        List<PromotionRuleEntity> promotionRuleEntityList = promotionRuleEntityMapper.queryByPromotionId(Long.parseLong(promotionAmountModel.getPromotionId()));
        // 首先获取阶梯等级最高的数据
        BigDecimal contentValue = super.getFlightContentValue(promotionAmountModel.getOverlayAppFlag(), promotionAmountModel.getOverlayAppNum(),  new BigDecimal(goodsPo.getNum()), promotionRuleEntityList, 1);

        // 不优惠处理
        if(null == contentValue || contentValue.compareTo(BigDecimal.ZERO) == 0){
            return false;
        }

        promotionAmountModel.setRuleData(contentValue);
        return true;
    }

    @Override
    protected BigDecimal promotionDiscountTotalAmount(PromotionAmountModel promotionAmountModel, GoodsPo goodsPo, Object request) {
        BigDecimal contentValue = (BigDecimal) promotionAmountModel.getRuleData();
        DiscountAmountQueryRequest discountAmountQueryRequest = (DiscountAmountQueryRequest) request;
        // 优惠总额 = 商品总价 - 优惠的运费
        BigDecimal promotionDiscountTotalAmount = null;
        if(null == discountAmountQueryRequest.getLogisticsFee()){
            promotionDiscountTotalAmount = BigDecimal.ZERO;
        }else if(discountAmountQueryRequest.getLogisticsFee().compareTo(BigDecimal.ZERO) == 0){
            promotionDiscountTotalAmount = BigDecimal.ZERO;
        }else if(discountAmountQueryRequest.getLogisticsFee().compareTo(contentValue) == 1){
            promotionDiscountTotalAmount = Money.subtract(goodsPo.getTotalAmount(), contentValue);
        }else if(discountAmountQueryRequest.getLogisticsFee().compareTo(contentValue) == -1){
            promotionDiscountTotalAmount = Money.subtract(goodsPo.getTotalAmount(), discountAmountQueryRequest.getLogisticsFee());
        }
        return promotionDiscountTotalAmount;
    }

}
